<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="动态标题" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入动态标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="动态详情" prop="nameDetail">
        <el-input v-model="queryParams.nameDetail" placeholder="请输入动态详情" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="热点排序" prop="top">
        <el-input v-model="queryParams.top" placeholder="请输入热点排序字段，值越小越靠前，NULL 表示非热点" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['activities:activity:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['activities:activity:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['activities:activity:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['activities:activity:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <!-- 多选框列 -->
      <el-table-column type="selection" width="55" align="center" />

      <!-- 序号列 -->
      <el-table-column type="index" label="序号" width="50" align="center" />

      <!-- 动态标题 -->
      <el-table-column label="动态标题" align="center" prop="name" />

      <!-- 动态详情 -->
      <el-table-column label="动态详情" align="center" prop="nameDetail">
        <template slot-scope="scope">
          <div class="ellipsis" :title="scope.row.nameDetail">{{ truncateText(scope.row.nameDetail) }}</div>
        </template>
      </el-table-column>

      <!-- 发布时间 -->
      <el-table-column label="发布时间" align="center">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>

      <!-- 热点排序 -->
      <el-table-column label="热点排序" align="center" prop="top" />

      <!-- 配图列 -->
      <el-table-column label="配图" align="center">
        <template slot-scope="scope">
          <!-- 循环展示每张图片 -->
          <div style="display: flex; flex-wrap: wrap; gap: 5px;">
            <el-image v-for="(picture, index) in scope.row.activityPictureMappingList" :key="index"
              :src="picture.pictureUrl" :preview-src-list="scope.row.activityPictureMappingList.map(p => p.pictureUrl)"
              style="width: 60px; height: 60px; object-fit: cover; border-radius: 5px;"></el-image>
          </div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['activities:activity:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['activities:activity:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改创客动态对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="动态标题" prop="name">
          <el-input v-model="form.name" placeholder="请输入动态标题" />
        </el-form-item>
        <el-form-item label="动态详情" prop="nameDetail">
          <el-input type="textarea" v-model="form.nameDetail" placeholder="请输入动态详情，不能超过200字" maxlength="200" :rows="3"
            :autosize="{ minRows: 3, maxRows: 5 }" show-word-limit />
        </el-form-item>

        <el-form-item label="热点排序" prop="top">
          <el-input v-model="form.top" placeholder="请输入热点排序字段，值越小越靠前，NULL 表示非热点" :readonly="true"
            style="width: 200px;" />
          <el-button type="primary" size="mini" @click="incrementTop" style="margin-left: 5px;">+</el-button>
          <el-button type="primary" size="mini" @click="decrementTop" style="margin-left: 5px;">-</el-button>
          <el-button type="warning" size="mini" @click="setTopNull" style="margin-left: 5px;">非热点</el-button>
        </el-form-item>

        <el-divider content-position="center">配图管理信息</el-divider>

        <!-- 显示已有的图片 -->
        <el-form-item label="已有配图">
          <el-row :gutter="20" class="image-row">
            <el-col v-for="(item, index) in activityPictureMappingList" :key="index" :span="8" class="image-container">
              <div class="image-wrapper">
                <img :src="item.pictureUrl" class="image" />
                <div class="delete-icon" @click="removeImage(index)">✖</div>
              </div>
            </el-col>
          </el-row>

        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload ref="upload" action="" list-type="picture-card" :multiple="true" :auto-upload="false"
            :file-list="fileList" :limit="9" :on-change="handleImageChange" :on-remove="handleImageRemove"
            :on-exceed="handleExceed" :before-upload="beforeUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listActivity, getActivity, delActivity, addActivity, updateActivity, uploadMultipleImages } from "@/api/activities/activity";
export default {
  name: "Activity",
  data() {
    return {
      uploading: false, // 防止重复提交的标记
      fileList: [], // 存储当前未上传的图片列表
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedActivityPictureMapping: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 创客动态表格数据
      activityList: [],
      // 配图管理表格数据
      activityPictureMappingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        nameDetail: null,
        top: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "动态标题不能为空", trigger: "blur" }],
        nameDetail: [
          { required: true, message: "动态详情不能为空", trigger: "blur" },
          { max: 200, message: "动态详情不能超过200字", trigger: "blur" }
        ],
        top: [
          {
            pattern: /^[0-9]*$/, // 匹配整数或空
            message: "热点排序字段必须是整数或留空",
            trigger: "blur"
          }
        ],
        createTime: [{ required: true, message: "发布时间不能为空", trigger: "blur" }]
      }


    };
  },
  created() {
    this.getList();
  },

  methods: {
    // 上传图片大小限制（不超过80M）
    beforeUpload(file) {
      const isLt80M = file.size / 1024 / 1024 < 80;
      if (!isLt80M) {
        this.$message.error('图片大小不能超过80MB!');
      }
      return isLt80M;
    },
    // 超出数量限制的处理方法
    handleExceed(files, fileList) {
      this.$message.warning('最多只能上传9张图片!');
    },
    // 删除已上传的图片
    removeImage(index) {
      this.activityPictureMappingList.splice(index, 1); // 从列表中移除该图片
    },
    // 上传图片变更事件
    handleImageChange(file, fileList) {
      const totalImages = this.activityPictureMappingList.length + fileList.length;
      if (totalImages > 9) {
        this.$message.warning('每条动态的配图不能超过9张！');
        return; // 阻止继续操作
      }
      this.fileList = fileList;
    },



    // 上传图片删除事件
    handleImageRemove(file, fileList) {
      this.fileList = fileList;
    },
    // 将 top 值递增
    incrementTop() {
      if (this.form.top === null || this.form.top === "") {
        this.form.top = 0; // 如果 top 为空或 null，则初始化为 0
      } else if (Number.isInteger(Number(this.form.top))) {
        this.form.top = Number(this.form.top) + 1;
      } else {
        this.$message.error("请输入合法的热点排序值！");
      }
    },
    // 将 top 值递减
    decrementTop() {
      if (this.form.top === null || this.form.top === "") {
        this.$message.warning("当前值为空，无法递减！");
      } else if (Number.isInteger(Number(this.form.top))) {
        if (this.form.top > 0) {
          this.form.top = Number(this.form.top) - 1;
        } else {
          this.$message.warning("当前值已为 0，无法递减！");
        }
      } else {
        this.$message.error("请输入合法的热点排序值！");
      }
    },
    // 设置 top 为 null
    setTopNull() {
      this.form.top = null; // 将值设置为 null
      this.$message.success("已设置为非热点！");
    },

    // 截断文本，超过的部分显示省略号
    truncateText(text) {
      if (!text) return '';  // 如果没有文本，则返回空字符串
      return text.length > 100 ? text.slice(0, 100) + '...' : text;
    },
    // 格式化日期为 年月日 形式
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = d.getMonth() + 1; // 月份是从0开始的
      const day = d.getDate();
      return `${year}-${month}-${day}`;
    },
    /** 查询创客动态列表 */
    getList() {
      this.loading = true;
      listActivity(this.queryParams).then(response => {
        console.log(response);
        this.activityList = response.rows;
        console.log(this.activityList);

        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.fileList = []; // 清空未上传的图片
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        activityId: null,
        name: null,
        nameDetail: null,
        createTime: null,
        top: null,
      };
      this.activityPictureMappingList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.activityId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加创客动态";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const activityId = row.activityId || this.ids
      getActivity(activityId).then(response => {
        this.form = response.data;
        this.activityPictureMappingList = response.data.activityPictureMappingList;
        this.open = true;
        this.title = "修改创客动态";
      });
    },

    /** 提交按钮 */
    async submitForm() {
      if (this.uploading) {
        this.$message.warning("正在上传，请稍后...");
        return;
      }

      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          // 检查当前图片总数
          const totalImages = this.activityPictureMappingList.length + this.fileList.length;
          if (totalImages > 9) {
            this.$message.warning('每条动态的配图不能超过9张！否则无法上传！');
            this.$message.warning('每条动态的配图不能超过9张！否则无法上传！');
            this.$message.warning('每条动态的配图不能超过9张！否则无法上传！');
            return;
          }

          // 防止重复提交
          this.uploading = true;

          try {
            // 上传图片
            const filesToUpload = this.fileList.map((file) => file.raw);
            if (filesToUpload.length > 0) {
              console.log(filesToUpload);
              
              const response = await uploadMultipleImages(filesToUpload);
              const uploadedUrls = response; // 假设后端返回图片链接数组

              uploadedUrls.forEach((url) => {
                this.activityPictureMappingList.push({ pictureUrl: url });
              });
            }

            // 保存表单
            this.form.activityPictureMappingList = this.activityPictureMappingList;
            if (this.form.activityId != null) {
              await updateActivity(this.form);
              this.$modal.msgSuccess("修改成功");
            } else {
              await addActivity(this.form);
              this.$modal.msgSuccess("添加成功");
            }

            this.open = false;
            this.fileList = []; // 清空未上传的图片
            this.getList();
          } catch (error) {
            this.$message.error("图片上传或保存失败，请重试！");
          } finally {
            this.uploading = false;
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const activityIds = row.activityId || this.ids;
      this.$modal.confirm('是否确认删除创客动态编号为"' + activityIds + '"的数据项？').then(function () {
        return delActivity(activityIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 配图管理序号 */
    rowActivityPictureMappingIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 配图管理添加按钮操作 */
    handleAddActivityPictureMapping() {
      let obj = {};
      obj.pictureUrl = "";
      this.activityPictureMappingList.push(obj);
      console.log(obj);
    },
    /** 配图管理删除按钮操作 */
    handleDeleteActivityPictureMapping() {
      if (this.checkedActivityPictureMapping.length == 0) {
        this.$modal.msgError("请先选择要删除的配图管理数据");
      } else {
        const activityPictureMappingList = this.activityPictureMappingList;
        const checkedActivityPictureMapping = this.checkedActivityPictureMapping;
        this.activityPictureMappingList = activityPictureMappingList.filter(function (item) {
          return checkedActivityPictureMapping.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleActivityPictureMappingSelectionChange(selection) {
      this.checkedActivityPictureMapping = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('activities/activity/export', {
        ...this.queryParams
      }, `activity_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.image-row {
  margin-bottom: 20px;
}

.image-container {
  position: relative;
  text-align: center;
}

.image-wrapper {

  position: relative;
  display: inline-block;
  width: 100%;
}

.image {
  width: 200px;
  height: 150px;
  border-radius: 5px;
  padding: 7px;
  /* border: 1px solid black; */
  /* 边框 */
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
  /* 阴影 */
}

.delete-icon {
  position: absolute;
  top: 2px;
  right: -20px;
  background-color: rgba(255, 0, 0);
  color: #fff;
  border-radius: 50%;
  cursor: pointer;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: background-color 0.3s;
}

.delete-icon:hover {
  background-color: rgba(255, 0, 0, 0.6);
}


.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
  display: inline-block;
}
</style>